//
//  LocationManager.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/12.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "LocationManager.h"
#import "GPSCorrect.h"

@interface LocationManager()

@property (strong, nonatomic) NSString *cityName;
@property (strong, nonatomic) NSString *cityCode;
@property (strong, nonatomic) NSString *serverDetectProvince;
@property (strong, nonatomic) NSString *serverDetectCity;
@property (nonatomic, assign) float longitude;
@property (nonatomic, assign) float latitude;
@property (nonatomic, copy) LocationBlock locationBlock;
@property (nonatomic, copy) LocationErrorBlock errorBlock;
@property (nonatomic, assign)BOOL isGetLocationInfo;


@end

@implementation LocationManager
+ (LocationManager *)shareLocation {
    static dispatch_once_t onceToken;
    __strong static id _sharedObject = nil;
    dispatch_once(&onceToken, ^{
        _sharedObject = [[self alloc] init];
    });
    return _sharedObject;
}

- (id)init {
    self = [super init];
    if (self) {
        self.locationManager = [[CLLocationManager alloc] init];
        self.locationManager.delegate = self;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters; //whenever we move
    }
    return self;
}

- (void)getLocationCoordinate:(LocationBlock) locaiontBlock error:(LocationErrorBlock) errorBlock {
    self.locationNativeAPiErrorBlock = nil;
    self.locationBlock = locaiontBlock;
    self.errorBlock = errorBlock;
    _isGetLocationInfo = NO;
    [self setLocationInfo];
}

- (BOOL)locationServicesEnabled {
    _servicesEnabled = [CLLocationManager locationServicesEnabled];
    return _servicesEnabled;
}

//判断是否有定位过，
- (void)setLocationInfo {
    if ([CLLocationManager locationServicesEnabled]) {
        [self.locationManager startUpdatingLocation];
    } else {
        if (_errorBlock) {
            NSError *error = [NSError errorWithDomain:@"定位失败" code:kCLErrorDenied userInfo:[[NSDictionary alloc] initWithObjectsAndKeys:@"不支持定位",@"errorInfo", nil]];
            _errorBlock(error);
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (kCLAuthorizationStatusDenied == status) {
        [self.locationManager stopUpdatingLocation];
    } else if (kCLAuthorizationStatusAuthorizedAlways == status) {
        [self.locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
    } else if (status == kCLAuthorizationStatusNotDetermined) {
        if ([manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [manager requestWhenInUseAuthorization];
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocatio {
    [self getNewLocation:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    //获得自己地理位置
    DLog(@"获得自己地理位置");
    CLLocation *newLocation = locations[0];
    [self getNewLocation:newLocation];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败:    %@",error);
    if ([error code] == kCLErrorDenied) {
        [self.locationManager stopUpdatingLocation];
        if (_errorBlock) {
            _errorBlock(error);
        }
    }
    if (self.locationNativeAPiErrorBlock) {
        self.locationNativeAPiErrorBlock(error);
    }
}

- (LocationInfo *)formateLocation:(CLLocationCoordinate2D)location withPlacemark:(CLPlacemark *)mkPlacemark {
    LocationInfo *mark = [[LocationInfo alloc] init];
    mark.country = mkPlacemark.country ? mkPlacemark.country : @"";
    mark.province = mkPlacemark.administrativeArea ? mkPlacemark.administrativeArea : @"";
    mark.city = mkPlacemark.locality ? mkPlacemark.locality : mark.province;
    mark.county = mkPlacemark.subLocality ? mkPlacemark.subLocality : @"";
    NSString *formatAddress = [NSString stringWithFormat:@"%@%@", mkPlacemark.thoroughfare ? mkPlacemark.thoroughfare : @"",
                               mkPlacemark.subThoroughfare ? mkPlacemark.subThoroughfare : @""];
    mark.address = formatAddress;
    mark.coordinate = location;
    
    if ([mark.province isEqualToString:mark.city]) {
        mark.city = mark.county;
    }
    
    if ([mark.province hasSuffix:@"市"] && mark.province.length > 1) {
        mark.province = [mark.province substringToIndex:mark.province.length - 1];
    }
    
    if ([mark.city hasSuffix:@"市"] && mark.city.length > 1) {
        mark.city = [mark.city substringToIndex:mark.city.length - 1];
    }
    
    if ([mark.city hasSuffix:@"县"] && mark.city.length > 1) {
        mark.city = [mark.city substringToIndex:mark.city.length - 1];
    }
    mark.city = [mark.city stringByReplacingOccurrencesOfString:@"特别行政区" withString:@""];
    mark.city = [mark.city stringByReplacingOccurrencesOfString:@"特別行政區" withString:@""];
    
    if ([mark.city isEqualToString:@"澳門"]) {
        mark.city = @"澳门";
    }
    
    return mark;
}

#pragma mark -- 向服务端获取定位信息
- (void)getNewLocation:(CLLocation *)newLocation {
    if (_isGetLocationInfo) {
        return;
    }
    _isGetLocationInfo = YES;
    CLLocationCoordinate2D correctedCoordinate = [GPSCorrect GCJFromWGSLat:newLocation.coordinate.latitude WGSLon:newLocation.coordinate.longitude];
    self.longitude = correctedCoordinate.longitude;
    self.latitude = correctedCoordinate.latitude;

    LocationInfo *info = [[LocationInfo alloc] init];
    info.coordinate = CLLocationCoordinate2DMake(self.latitude, self.longitude);
    if (self.locationBlock) {
        self.locationBlock(info);
    }
    NSLog(@"\n=====================\n 经纬度：%f,%f \n====================",self.latitude,self.longitude);
}


@end

@implementation LocationInfo

- (void)updateWithLocationDic:(NSDictionary *)locationDic {
    NSString *city = [locationDic objectForKey:@"city"];
    if (city) {
        self.city = city;
    }
    NSString *province = [locationDic objectForKey:@"province"];
    if (province) {
        self.province = province;
    }
    
    NSNumber *lat = [locationDic objectForKey:@"latitude"];
    NSNumber *lon = [locationDic objectForKey:@"longitude"];
    if (lat && lon) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake([lat floatValue], [lon floatValue]);
        self.coordinate = coordinate;
    }
    
}


@end
